from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.views import View
from django import http
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection
from meixixi.utils.my_openid import encode_openid,decode_openid
from users.models import User
from .models import OAuthQQUser


class QQLoginView(View):
    def get(self,request):
        #1,创建qq对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')

        #2,获取qq登录页面
        login_url = oauth_qq.get_qq_url()

        #3,返回响应
        return http.JsonResponse({
            "login_url":login_url
        })


class OAuthCallBackView(View):
    def get(self,request):
        #1,获取参数
        code = request.GET.get("code")

        #2,校验参数
        if not code:
            return http.HttpResponseForbidden("code丢失")

        #3,获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')
        access_token = oauth_qq.get_access_token(code=code)

        #4,获取openid
        openid = oauth_qq.get_open_id(access_token=access_token)

        #5,通过openid,查询qq用户
        try:
            qq_user = OAuthQQUser.objects.get(open_id=openid)

        except Exception as e:
            encrypt_openid = encode_openid(openid)
            context = {
                'token':encrypt_openid
            }
            return http.HttpResponseForbidden(request,'oauth_callback.html',context=context)
        else:
            user = qq_user.user
            login(request,user)
            response = redirect('/')
            response.set_cookie('username', user.username)
            return response


    def post(self,request):
        encry_openid = request.POST.get('access_token')
        mobile = request.POST.get('mobile')
        password = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')
        openid = decode_openid(encry_openid)

        if not openid:
            return http.HttpResponseForbidden('openid过期')

        if not all([encode_openid,mobile,password,sms_code]):
            return http.HttpResponseForbidden('参数不全')

        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_code_%s'%mobile)

        if not redis_sms_code:
            return http.HttpResponseForbidden('短信过期')

        if sms_code != redis_sms_code.decode():
            return http.HttpResponseForbidden('短信错误')

        user = authenticate(request,mobile=mobile,password=password)

        if user:
            qq_user = OAuthQQUser()
            qq_user.user = user
            qq_user.open_id = openid
            qq_user.save()
            login(request,user)
            response = redirect('/')
            response.set_cookie('username',user.username)
            return response

        else:
            user = User.objects.create_user(username=mobile,password=
                                            password,mobile=mobile)
            qq_user = OAuthQQUser.objects.create(user=user,
                                                 open_id=openid)
            login(request,user)
            response = redirect('/')
            response.set_cookie('username',user.username)
            return response